<template>
	<view class="qrcode-container">
		<canvas canvas-id="qrcodeCanvas" type="2d" :width="size" :height="size" class="qrcode-canvas"></canvas>
	</view>
</template>
 
<script>
import QRCode from 'qrcode';
 	export default {
		data() {
      return {}
    },
    props:{
      content: {
        type: String,
        required: true
      },
      size: {
        type: Number,
        default: 130
      }
    },
    watch:{
      content(){
        	this.generateQRCode();
      }
    },
    mounted(){
      	this.generateQRCode();
    },
    methods:{
  async  generateQRCode(){
  try {
		// 检查内容是否为空
		if (!this.content || !this.content.trim()) {
			console.warn('二维码内容不能为空');
			uni.showToast({
				title: '二维码内容不能为空',
				icon: 'none'
			});
			return;
		}
 
		// 在UniApp中获取canvas上下文的正确方式
		const ctx = uni.createCanvasContext('qrcodeCanvas', this);
 
		// 将内容转换为二维码并绘制到canvas
		const imgData = await QRCode.toDataURL(this.content, {
			width: this.size,
			margin: 1
		});
		// 将图片绘制到canvas
		ctx.drawImage(imgData, 0, 0, this.size, this.size);
		ctx.draw();
	} catch (error) {
		console.error('生成二维码失败:', error);
		uni.showToast({
			title: '生成二维码失败',
			icon: 'none'
		});
	}
}
    }
   }


</script>
 
<style scoped>
.qrcode-container {
	display: flex;
	justify-content: center;
	align-items: center;
}
 
.qrcode-canvas {
	background-color: #fff;
  width:130px;
  height: 130px;
}
</style>